<?php

namespace app\admin\controller;
use app\lib\enum\Status;

class Role extends BaseController
{
    // 身份权限列表
    public function roleList(){
        if(!judgeRole(__METHOD__)){
            $this->redirect("admin/index/forbidden");
        }
        if(request()->isAjax()){
            $info = model("CmsRole")->select();
            $count = count($info);
            return getJson($count, $info);
        }
        return view();
    }


    //角色编辑
    public function roleEdit(){
        if (request()->isAjax()) {
            $array = input("post.rol_list/a");
            $rol_list = "";
            if ($array != null) {
                foreach ($array as $key => $value) {
                    if (isset($value)) {
                        $rol_list .= $value . "|";
                    }
                }
                $rol_list = trim($rol_list, "|");
            }

            $rol_id = input("post.rol_id");
            $data = [
                "rol_name" => input("post.rol_name"),
                "rol_remark" => input("post.rol_remark"),
                "rol_list" => $rol_list
            ];
            $result = model("CmsRole")->roleEdit($data, $rol_id);
            $this->uniteResponse($result,"信息更新成功");
        }
        $rol_id=input("get.rol_id");
        $roleInfo=model("CmsRole")->find($rol_id);
        $rol_list = $roleInfo['rol_list'];
        $checkBoxData = [];
        //获取该角色的权限信息，组装为数据
        $rol_list_array = explode("|", $rol_list);
        $roleMsg = getRoleList();
        foreach ($roleMsg as $key => $value) {
            $checkBoxData[] = [
                "key" => $key,
                "value" => $value,
                "isCheck" => in_array($key, $rol_list_array) ? Status::on: Status::off
            ];
        }

        $this->assign("roleInfo",$roleInfo);
        $this->assign("checkBoxData",$checkBoxData);
        return view();
    }

    //角色添加
    public function roleAdd(){
        if(request()->isAjax()){
            //"/a"表示获取全部名称为rol_list的数据，组成数组格式。
            //用于获取checkbox的所有选择值
            $array = input("post.rol_list/a");
            $rol_list = "";
            if ($array != null) {
                foreach ($array as  $value) {
                    if (isset($value)) {
                        $rol_list .= $value . "|";
                    }
                }
                $rol_list = trim($rol_list, "|");
            }
            $data=[
                "rol_name"=>input("post.rol_name"),
                "rol_remark"=>input("post.rol_remark"),
                "rol_list"=>$rol_list,
            ];
            $this->uniteResponse(model("CmsRole")->roleAdd($data),"角色添加成功");
        }

        $roleList=getRoleList();
        $checkBoxData=[];
        foreach($roleList as $key=>$value){
            $checkBoxData[]=[
                "key"=>$key,
                "value"=>$value
            ];
        }
        $this->assign("checkBoxData",$checkBoxData);
        return view();
    }
}
